package com.bodgittandscarper.broker.server;

import static java.util.logging.Level.INFO;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.logging.Logger;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.bodgittandscarper.broker.utils.PropertyHandler;
/**
 * ServerStartupDialog is a dialog for presenting and editing server properties. It uses the PropertyHandler to access a 
 * property file specified for the application. 
 * <p>
 * The dialog provides blocking facility. When the dialog is shown, the caller thread will wait until the dialog is closed.
 * This can happen in either of the two cases: If the dialog is closed with the window close icon, the dialog will simply exit.
 * Or if the dialog is closed normally by pressing the OK button the waiting thread will be notified.   
 * 
 * @author Morten Rummelhoff
 * @see #show()
 */
public class ServerStartupDialog extends JDialog {

	private static final long serialVersionUID = 1L;

	private Logger log = Logger.getLogger(getClass().getName());
	
	private JTextField textField;
	private JLabel statusLabel;
	
	private static final String DB_FILE_PROPERTY_NAME = "database_file_name"; 
		
	/**
	 * Constructor initializing the dialog. The property file is read, and any stored values are presented.  
	 * <p>
	 * The dialog is not shown until the <code>show</code> method is invoked.
	 */
	@SuppressWarnings("serial")
	public ServerStartupDialog() {
		super(new JFrame(), "Bodgitt & Scarper - Locate Database", true);
		
		final JPanel mainPanel = new JPanel(new BorderLayout());
		
		final JPanel rowPanel = new JPanel();
		rowPanel.setLayout(new BoxLayout(rowPanel, BoxLayout.Y_AXIS));
		rowPanel.setBorder(BorderFactory.createTitledBorder("Database Setup:"));
		
		JPanel dbPanel = new JPanel();
		dbPanel.add(new JLabel("Location: "));
		rowPanel.add(dbPanel);
	
		Action okAction = new AbstractAction("Ok") {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if (log.isLoggable(INFO)) {
					log.log(INFO, "Pressing ok.");
				}
				
				if (validateFile()) {
					PropertyHandler.getInstance().setProperty(DB_FILE_PROPERTY_NAME, textField.getText());
					PropertyHandler.getInstance().storeProperty();
					
					setVisible(false);
					
				}
				else {
					statusLabel.setText("File does not exit..");
				}
				
			}
		};
		
		Action cancelAction = new AbstractAction("Cancel") {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if (log.isLoggable(INFO)) {
					log.log(INFO, "Cancel pressed, Get old stored value from propertyfile.");
				}
				textField.setText(PropertyHandler.getInstance().getProperty(DB_FILE_PROPERTY_NAME));
			}
		};
		
		
		JPanel buttonPanel = new JPanel();
		JButton okButton = new JButton(okAction);
		
		buttonPanel.add(okButton);
		buttonPanel.add(new JButton(cancelAction));
		
		rowPanel.add(buttonPanel);
		
		JPanel statusPanel = new JPanel();
		statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));

		statusLabel = new JLabel("Select database.");

		statusPanel.add(Box.createHorizontalStrut(4));
		statusPanel.add(statusLabel);
		statusPanel.add(Box.createVerticalStrut(21));

		statusPanel.setBorder(BorderFactory.createLoweredBevelBorder());

		mainPanel.add(statusPanel, BorderLayout.SOUTH);
		
		//Create a file chooser
		final JFileChooser fc = new JFileChooser();
		
		textField = new JTextField(PropertyHandler.getInstance().getProperty(DB_FILE_PROPERTY_NAME));
		textField.setColumns(25);
		
		dbPanel.add(textField);
		mainPanel.add(rowPanel, BorderLayout.CENTER);
		JButton openButton = new JButton("Open File...");
		openButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				fc.showOpenDialog(mainPanel);
				
				File selectedFile = fc.getSelectedFile();
				if (selectedFile != null) {
					textField.setText(selectedFile.toString());
				}
			}	
			
		});
		dbPanel.add(openButton);
		add(mainPanel);
		
		pack();
		setLocationRelativeTo(null);
		
		addWindowListener(new WindowAdapter() {
			
			@Override
			public void windowClosing(WindowEvent e) {
				
				//If Dialog is about to close, i.e. user has pressed default close window icon, exit program.
				System.exit(0);
			}
			
		
		});
		
		okButton.requestFocus();
	}
	
	private boolean validateFile() {
		//for now, just check if file exist
		File file = new File(textField.getText());
		return file.exists();
		
	}

	/**
	 * Gets the location of the Database file. This method returns the value from the text field of the dialog. 
	 * This means that the database location is always available even if the property file somehow got unaccessible.
	 * 
	 * This method normally returns a value that is equal to the value read from the property file.
	 * 
	 * @return String representation of the location of the DatabaseFile
	 */
	public String getDBFile() {
		return textField.getText();
	}

	
}
